package sfs

import (
	"fmt"
	"io"
	"os"
	"time"
)

// DirInfo is a static definition of a directory.
type DirInfo struct {
	name    string
	modTime time.Time
	entries []os.FileInfo
}

func (d *DirInfo) Read([]byte) (int, error) {
	return 0, fmt.Errorf("cannot Read from directory %s", d.name)
}
func (d *DirInfo) Close() error               { return nil }
func (d *DirInfo) Stat() (os.FileInfo, error) { return d, nil }

func (d *DirInfo) Name() string       { return d.name }
func (d *DirInfo) Size() int64        { return 0 }
func (d *DirInfo) Mode() os.FileMode  { return 0755 | os.ModeDir }
func (d *DirInfo) ModTime() time.Time { return d.modTime }
func (d *DirInfo) IsDir() bool        { return true }
func (d *DirInfo) Sys() interface{}   { return nil }

// Dir is an opened dir instance.
type Dir struct {
	*DirInfo
	pos int // Position within entries for Seek and Readdir.
}

func (d *Dir) Seek(offset int64, whence int) (int64, error) {
	if offset == 0 && whence == io.SeekStart {
		d.pos = 0
		return 0, nil
	}
	return 0, fmt.Errorf("unsupported Seek in directory %s", d.name)
}

func (d *Dir) Readdir(count int) ([]os.FileInfo, error) {
	if d.pos >= len(d.entries) && count > 0 {
		return nil, io.EOF
	}
	if count <= 0 || count > len(d.entries)-d.pos {
		count = len(d.entries) - d.pos
	}
	e := d.entries[d.pos : d.pos+count]
	d.pos += count
	return e, nil
}
